package app.hanxiao.com.demo.push.Factory;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

//防止数据丢失
public class MyTextLineCumulativeDecoder extends CumulativeProtocolDecoder {

	private String codeFormat_GB2312 = "GB2312";
	private String codeFormat_UTF = "GB2312";
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		int startPosition = in.position();
		//是否还有字节可以读取
		while(in.hasRemaining()){
			byte b = in.get();
			if (b == '\n') {
				int currentPosition = in.position();
				int limit = in.limit();
				in.position(startPosition);
				in.limit(currentPosition);
				//截取一行
				IoBuffer buf = in.slice();
				byte[] dest = new byte[buf.limit()];
				buf.get(dest);
				String str = new String(dest,codeFormat_UTF);
				out.write(str);
				//位置还原
				in.position(currentPosition);
				in.limit(limit);
				return true;
			}
		}
		in.position(startPosition);
		return false;
	}

}
